#include "statisticswindow.h"
#include <QPainter>
#include <QSqlQuery>
#include <QDebug>
#include <algorithm>

StatisticsWindow::StatisticsWindow(QWidget *parent) : QWidget(parent)
{
    setMinimumSize(800, 600);
}

QVector<StatisticsWindow::SalesData> StatisticsWindow::loadSalesData()
{
    QVector<SalesData> data;
    QSqlQuery query;
    query.exec("SELECT p.name, SUM(o.total_price) FROM orders o "
               "JOIN products p ON o.product_id = p.product_id "
               "GROUP BY p.name");

    while(query.next()) {
        data.append({query.value(0).toString(), query.value(1).toDouble()});
    }

    // 按销售额排序
    std::sort(data.begin(), data.end(), [](const SalesData &a, const SalesData &b) {
        return a.salesAmount > b.salesAmount;
    });

    return data;
}

void StatisticsWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 1. 绘制背景
    painter.fillRect(rect(), QColor(240, 240, 240));

    // 2. 加载数据
    auto salesData = loadSalesData();
    if(salesData.isEmpty()) return;

    // 3. 计算最大值用于比例缩放
    double maxSales = 0;
    for(const auto &item : salesData) {
        if(item.salesAmount > maxSales) maxSales = item.salesAmount;
    }

    // 4. 绘制柱状图
    const int margin = 50;
    const int barWidth = 60;
    const int spacing = 30;

    painter.setPen(Qt::black);
    painter.drawText(20, 30, "鲜花销售额统计");

    // X轴和Y轴
    painter.drawLine(margin, height() - margin, width() - margin, height() - margin); // X轴
    painter.drawLine(margin, margin, margin, height() - margin); // Y轴

    // 绘制柱子和标签
    for(int i = 0; i < salesData.size(); ++i) {
        const auto &item = salesData[i];
        int x = margin + spacing + i * (barWidth + spacing);
        int barHeight = static_cast<int>((item.salesAmount / maxSales) * (height() - 2 * margin - 30));

        // 柱子
        painter.setBrush(QColor(65, 105, 225));
        painter.drawRect(x, height() - margin - barHeight, barWidth, barHeight);

        // 销售额标签
        painter.drawText(x, height() - margin - barHeight - 10,
                        QString("¥%1").arg(item.salesAmount, 0, 'f', 0));

        // 商品名称
        painter.save();
        painter.translate(x + barWidth/2, height() - margin + 20);
        painter.rotate(45);
        painter.drawText(0, 0, item.productName);
        painter.restore();
    }

    // 5. 绘制图例
    painter.setPen(Qt::black);
    painter.drawText(width() - 150, 30, "商品销售排行");
    for(int i = 0; i < qMin(5, salesData.size()); ++i) {
        painter.setBrush(QColor(65, 105, 225));
        painter.drawRect(width() - 180, 50 + i * 30, 15, 15);
        painter.drawText(width() - 160, 60 + i * 30,
                        QString("%1. %2").arg(i+1).arg(salesData[i].productName));
    }
}
